<script setup lang="ts">
import {reactive, ref} from "vue";
import {ElMessage, ElMessageBox, FormInstance} from "element-plus";
import {adminEditAdmin} from "@/router/api"
import {adminUserStore} from "@/stores/adminStore";
import {useRouter} from "vue-router";
import {md5} from 'js-md5';

const router = useRouter(); // 获取路由实例
const adminStore = adminUserStore()
const showMessage = (type:any, message:any) => {// 显示消息提示
  ElMessage({
    type,
    message,
    duration: 1000,
  });
};
const rules = {
  account: [
    {required: true, message: '请输入账号', trigger: 'blur'},
    {min: 2, max: 10, message: '账号长度在 2 到 10 个字符', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 2, max: 10, message: '密码长度在 2 到 10 个字符', trigger: 'blur'},
  ],
  confirmPassword: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {
      validator: (rule:any, value:any, callback:any) => {
        if (value !== editForm.password) {
          callback('两次密码输入不一致!');
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
}
const editFormRef = ref<FormInstance>();
const editForm = reactive({
  id: adminStore.adminInfo.id,
  account: adminStore.adminInfo.account,
  password: '',
  confirmPassword: '',
})
const oldPassword = ref('');
const errMsg = ref('');
//修改管理员
const handleEdit = () => {
  editFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const old_password = md5(oldPassword.value);
        const password = md5(editForm.password);
        if (isEditAccount.value && old_password != adminStore.adminInfo.password) {
          errMsg.value = "请输入正确的原密码";
          return;
        }
        if (!isEditAccount.value && password != adminStore.adminInfo.password) {
          errMsg.value = "密码错误";
          return;
        }
        if (editForm.password !== editForm.confirmPassword) {
          errMsg.value = "两次密码输入不一致";
          return;
        }
        await adminEditAdmin(editForm);
        adminStore.adminInfo.account = editForm.account;
        adminStore.adminInfo.password = editForm.password;
        editFormRef.value?.resetFields();
        editForm.account = ''
        editForm.password = ''
        await router.replace('/login-register');
        showMessage("success", "编辑成功");
      } catch (error) {
        showMessage("error", "编辑失败");
      }
    } else {
      showMessage("warning", "请确保所有字段都填写完整！");
    }
  });
}

// 退出登录
const logout = () => {
  ElMessageBox({
    title: '退出登录',
    message: '确认退出登录？',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    center: true,  // 中心对齐
  }).then(async () => {
    adminStore.logout();
    await router.replace('/login-register');
    showMessage('success', "退出登录成功")
  })
    .catch(() => {
      showMessage('info', "取消退出登录");
    });
};
const isEditAccount = ref(true);
const toggleEditAccount = () => {
  editForm.password = '';
  editForm.confirmPassword = '';
  oldPassword.value = '';
  errMsg.value = '';
  if (isEditAccount.value) {
    editForm.account = '';
  } else {
    editForm.account = adminStore.adminInfo.account;
  }
  isEditAccount.value = !isEditAccount.value;
  console.log(isEditAccount.value);
}
</script>

<template>
  <div class="admin-card">
    <el-card style="width: 90%; height: 90%;" shadow="always" body-class="body-card">
      <div class="card1">
        <img src="/adminBackground.png" alt="" class="img-fluid"/>
        <el-avatar :size="100" class="avatar"/>
        <div class="info-container">
          <div><strong>账号信息：</strong>{{ adminStore.adminInfo.account }}</div>
          <div><strong>登录时间：</strong>{{ adminStore.adminInfo.last_login_time }}</div>
          <div><strong>登录地点：</strong>{{ adminStore.adminInfo.last_login_ip }}</div>
        </div>
        <div class="logout-btn">
          <el-button type="danger" @click="logout" size="large" plain>退出登录
          </el-button>
        </div>
      </div>
      <div class="card2">
        <h1>{{ isEditAccount ? '修改密码界面' : '修改账号界面' }}</h1>
        <p v-if="errMsg" style="color: red">{{ errMsg }}</p>
        <el-button type="warning" plain @click="toggleEditAccount" size="large"
                   style="margin-bottom: 20px">
          {{ !isEditAccount ? '修改密码' : '修改账号' }}
        </el-button>
        <el-form :model="editForm"
                 ref="editFormRef"
                 :rules="rules"
                 status-icon
                 scroll-to-error
                 size="large">
          <el-form-item label="账号信息" prop="account">
            <el-input v-model="editForm.account" placeholder="请输入账号"
                      :disabled="isEditAccount"/>
          </el-form-item>
          <el-form-item label="输入原密码" v-show="isEditAccount">
            <el-input v-model="oldPassword" placeholder="请输入原密码" type="password"
                      show-password/>
          </el-form-item>
          <el-form-item label="请修改密码" prop="password" v-show="isEditAccount">
            <el-input v-model="editForm.password" placeholder="请修改密码" type="password"
                      show-password/>
          </el-form-item>
          <el-form-item label="请输入密码" prop="password" v-show="!isEditAccount" validate-event>
            <el-input v-model="editForm.password" placeholder="请输入密码" type="password"
                      show-password/>
          </el-form-item>
          <el-form-item label="请确认密码" prop="confirmPassword">
            <el-input v-model="editForm.confirmPassword" placeholder="请确认密码" type="password"
                      show-password/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleEdit" size="large">修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<style>
.logout-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 40px auto 0 auto;
}

.info-container {
  margin: 20px auto;
  width: 65%;
  height: 25%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: start;
  padding: 10px;
}

.avatar {
  margin-top: -55px;
  margin-left: 170px;
}

.img-fluid {
  width: 100%;
  height: 40%;
  object-fit: cover;
}

.admin-card {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.body-card {
  width: 100%;
  height: 95%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row;
}

.card1 {
  border: 1px solid #cccccc;
  width: 42%;
  height: 100%;
  border-radius: 10px;
  overflow: hidden;
}

.card2 {
  border: 1px solid rosybrown;
  width: 50%;
  height: 100%;
  margin-right: 5%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
